package com.adcc.foc.service;

import com.adcc.foc.IDao.AuthRoleMapper;
import com.adcc.foc.IDao.OrgMapper;
import com.adcc.foc.IDao.UserMapper;
import com.adcc.foc.IDao.User_RoleMapper;
import com.adcc.foc.config.AppConfig;
import com.adcc.foc.domain.*;
import com.adcc.foc.utils.DateUtil;
import com.adcc.foc.utils.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by houxy on 2016/8/2.
 * userService的实现类
 *
 * @author houxy
 */
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private AuthRoleMapper authRoleMapper;
    @Resource
    private User_RoleMapper user_roleMapper;
    @Resource
    private OrgMapper orgMapper;
    @Resource
    private AppConfig appConfig;
    private static final String DEFAULT_PASSWORD = "123456";


    /**
     * 检查用户登录逻辑
     *
     * @param userName 用户名
     * @author houxy
     */
    @Override
    public User checkLogin(String userName) {
        User user = userMapper.findUser(userName);
        return user;
    }

    /**
     * 获取所有用户信息及其组织信息
     *
     * @author houxy
     */
    @Override
    public List<User> findAllUser() {
        List<User> users = userMapper.findAll();
        return users;
    }

    /**
     * 删除用户信息
     *
     * @author houxy
     */
    @Override
    public Map<String, Object> deleteUser(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int isSuccess = userMapper.deleteUser(id);
        user_roleMapper.deleteByUserId(id);
        map.put("msg", "删除成功！");
        return map;
    }

    /**
     * 新建用户
     *
     * @param username 用户名
     * @param password 密码
     * @param orgid    部门id
     * @author houxy
     */
    @Override
    public Map<String, Object> saveUser(String username, String password, String orgid, String compelltion, String roleId) {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = userMapper.findUser(username);
        if (user != null) {
            map.put("msg", "该账号已存在！");
            return map;
        }
        User newUser = new User();
        password = UserUtil.MD5(password);
        newUser.setUsername(username);
        newUser.setOrgid(orgid);
        newUser.setPassword(password);
        newUser.setCompelltion(compelltion);
        newUser.setPasswordUpdateTime(new Date());
        userMapper.saveUser(newUser);
        if (roleId != null && !"".equals(roleId)) {
            User_Role record = new User_Role();
            record.setRoleId(roleId);
            record.setUserId(newUser.getId());
            user_roleMapper.insert(record);
        }
        map.put("msg", "添加成功！");
        return map;
    }

    /**
     * 修改用户信息
     *
     * @param userId 用户id
     * @param orgid  转入的部门id
     * @author houxy
     */
    @Override
    public Map<String, Object> alterUser(String userId, String orgid, String roleId, String compelltion) {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setId(userId);
        user.setCompelltion(compelltion);
        if (orgid != null && !"".equals(orgid)) {
            user.setOrgid(orgid);
        }
        userMapper.alterUser(user);
        user_roleMapper.deleteByUserId(userId);
        if (roleId != null && !"".equals(roleId)) {
            User_Role record = new User_Role();
            record.setRoleId(roleId);
            record.setUserId(userId);
            user_roleMapper.insert(record);
        }
        map.put("msg", "修改成功！");
        return map;
    }

    /**
     * 通过用户id查询登录者是否有维护用户和维护组织结构的权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<AuthRole> findRoleByUserId(String userId) {
        return authRoleMapper.findByUserId(userId);
    }

    /**
     * 获取登录者所在飞行队的下属人员
     *
     * @return
     */
    @Override
    public List<User> findUserByLoaderOrgId(String orgId) {
        return userMapper.findUserByLoaderOrgId(findRoot(orgId));
    }

    /**
     * 通过用户名查询当前用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public User findUserByUserName(String userName) {
        return userMapper.findUser(userName);
    }

    /**
     * 条件查询人员（数量）
     *
     * @param paramMap
     * @return
     */
    @Override
    public Long PageCounts(Map<String, Object> paramMap) {
        return userMapper.pageCounts(paramMap);
    }

    /**
     * 条件查询人员
     *
     * @param paramMap
     * @return
     */
    @Override
    public List<User> findByCondition(Map<String, Object> paramMap) {
        return userMapper.findByCodition(paramMap);
    }

    /**
     * 获取当前用户可以维护的部门和权限
     *
     * @param orgId
     * @return
     */
    @Override
    public Map<String, Object> findDeptAndRoles(String orgId, String isShowAll) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Organization> orgList = null;
        if ("0".equals(isShowAll) || "1".equals(isShowAll)) {
            orgList = orgMapper.findAll();
        } else if ("2".equals(isShowAll)) {
            //获取可以维护的部门
            orgList = orgMapper.findOrgsByOrgId(findRoot(orgId));
        }
        //获取所有权限
        List<AuthRole> roles = authRoleMapper.findAll();
        //把组织转换为可被z-tree识别的形式
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        for (Organization org : orgList) {
            TreeNode treeNode = new TreeNode(org.getId(), org.getPid(), org.getDeptname(), "true");
            treeNodeList.add(treeNode);
        }
        map.put("orgs", treeNodeList);
        map.put("roles", roles);
        return map;
    }

    /**
     * 查找当前部门的根节点
     *
     * @param orgId
     * @return
     */
    public String findRoot(String orgId) {
        //反推回当前部门的所有上级部门，所以根节点为list最后一个部门
        List<Organization> list = orgMapper.findRoot(orgId);
        return list.get(list.size() - 1).getId();
    }

    /**
     * 获取要修改用户的信息
     *
     * @param orgId
     * @param isShowAll
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> findUserInfoAndDeptAndRoles(String orgId, String isShowAll, String userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Organization> orgList = null;
        if ("0".equals(isShowAll) || "1".equals(isShowAll)) {
            orgList = orgMapper.findAll();
        } else if ("2".equals(isShowAll)) {
            //获取可以维护的部门
            orgList = orgMapper.findOrgsByOrgId(findRoot(orgId));
        }
        //获取所有权限
        List<AuthRole> roles = authRoleMapper.findAll();
        TreeNode treeNode = new TreeNode();
        //把组织转换为可被z-tree识别的形式
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        for (Organization org : orgList) {
            treeNode = new TreeNode(org.getId(), org.getPid(), org.getDeptname(), "true");
            treeNodeList.add(treeNode);
        }
        //获取选取用户已有的权限
        List<AuthRole> role = authRoleMapper.findByUserId(userId);
        AuthRole authRole = null;
        if (role.size() > 0) {
            authRole = role.get(0);
        }
        User user = userMapper.findUserById(userId);
        map.put("authRole", authRole);
        map.put("orgs", treeNodeList);
        map.put("roles", roles);
        map.put("user", user);
        return map;
    }

    @Override
    public void updateUser(User user) {
        userMapper.alterUser(user);
    }

    /**
     * 重置选中用户密码
     *
     * @param userId
     */
    @Override
    public void forceResetPassword(String userId) {
        Date updateTime = DateUtil.createRestPasswordTime(appConfig.getPasswordInvalid(),appConfig.getPasswordRemind());
        String password = UserUtil.MD5(DEFAULT_PASSWORD);
        User user = new User();
        user.setId(userId);
        user.setPassword(password);
        user.setPasswordUpdateTime(updateTime);
        userMapper.forceResetPassword(user);
    }
}
